<?php

namespace App\Http\Requests;

use App\Models\Auxiliary\AuxiliaryCheckEntry;
use App\Models\Patient;
use Illuminate\Database\Query\Builder;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Validator;

class AuxiliaryCheckStoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    public function withValidator(Validator $validator)
    {
        $validator->after(function (Validator $validator) {
            $exists = AuxiliaryCheckEntry::where([
                'record_id' => $this->input('record_id'),
                'check_type' => $this->input('check_type'),
            ])->exists();

            if ($exists) {
                $validator->messages()->add('check_type', '已添加过此项检查。');
            }
        });
    }

    /**
     * Get the validation rules that apply to the request.
     * @return array
     */
    public function rules()
    {
        return [
            'record_id'  => [
                'required', 'integer', 'min:1',
                Rule::exists('st_medical_records', 'id')->where(function (Builder $query) {
                    $query->whereNull('deleted_at');
                    $user = \Auth::user();
                    if ($user instanceof Patient) {
                        $query->where(['patient_id' => $user->id]);
                    } elseif (!$user->isDoctorsAdmin() && !$user->isAdmin()) {
                        $query->where(['doctor_id' => $user->id]);
                    }
                }),
            ],
            'image_file' => 'required|array|min:0|max:9|nullable',
            'remark'     => 'max:500|nullable',
            'check_type' => 'required|in:' . implode(',', array_keys(config('custom.auxiliary.check'))),
        ];
    }
}
